import { useEffect, useState, useRef } from 'react'
import { NavBar, Input, Card } from 'antd-mobile'
import type { SwiperRef } from 'antd-mobile/es/components/swiper'
import { Tabs, Swiper } from 'antd-mobile'
import { Swiper as ReactVantSwiper, Image } from 'react-vant'
import { CloseOutline, SearchOutline } from 'antd-mobile-icons'
import Doctor from '../../components/doctor/Doctor'
import ServiceSection from '../../components/ServiceSection/ServiceSection'
import styles from './home.module.scss'
import img from '../../assets/hb_03.jpg'
import dgimg from '../../assets/dg2_03.jpg'
import { Grid } from 'antd-mobile'
import ContentList from '../../components/common/ContentList'
import { useAppDispatch, useAppSelector, type RootState } from '../../store/store'
import { fetchHomepageData, resetHomepageState } from '../../store/homepageSlice';
import { useNavigate, useLocation } from 'react-router-dom'
const Index = () => {
    const dispatch = useAppDispatch()
    const { data } = useAppSelector((state: RootState) => state.homepage)
    const navigate = useNavigate()
    const location = useLocation()
    
    useEffect(() => {
        dispatch(fetchHomepageData())
        return () => {
            dispatch(resetHomepageState())
        }

    }, [dispatch])
    const swiperRef = useRef<SwiperRef>(null)
    const [activeIndex, setActiveIndex] = useState(1)
    const [searchValue, setSearchValue] = useState('')
    // 占位上下滚动：与 shopp 页面一致
    const placeholders = [
        '盐酸西替利嗪片',
        '糠酸莫米松乳膏',
        '布洛芬缓释胶囊',
        '板蓝根颗粒',
        '维生素C泡腾片'
    ]
    const [phIndex, setPhIndex] = useState(0)
    // 顶部胶囊提示相关
    const [pillVisible, setPillVisible] = useState(false)
    const [pillText, setPillText] = useState('')
    const tabItems = [
        { key: 'hot ', title: '热点' },
        { key: 'expert', title: '专家科普' },
        { key: 'Life', title: '生活' },
        { key: 'Maternal ', title: '母婴' },
        { key: 'Debunk', title: '辟谣' },
    ]

    // 搜索相关函数
    const handleSearchChange = (value: string) => {
        setSearchValue(value)
    }

    const handleSearchSubmit = () => {
        if (searchValue.trim()) {
            navigate(`/search?q=${encodeURIComponent(searchValue.trim())}`, {
                state: { from: location.pathname }
            })
        } else {
            navigate('/search', {
                state: { from: location.pathname }
            })
        }
    }

    const clearSearchInput = () => {
        setSearchValue('')
    }
    // 定时切换占位文案
    useEffect(() => {
        if (searchValue) return
        const timer = setInterval(() => {
            setPhIndex((idx) => (idx + 1) % placeholders.length)
        }, 3000)
        return () => clearInterval(timer)
    }, [searchValue])

    const getRollingText = (): string => {
        if (searchValue) return ''
        return placeholders[phIndex % placeholders.length]
    }

    // 生成随机胶囊提示文案
    const makeRandomPillText = () => {
        const regions = ['北京','上海','广州','深圳','杭州','成都','重庆','贵州','苏州','南京','武汉','西安']
        const actions = ['发起了问诊','正在咨询医生','完成了复诊咨询']
        const topics = ['感冒发烧','鼻炎不适','皮肤过敏','胃部不适','咳嗽喉咙痛']
        const rand = (arr: string[]) => arr[Math.floor(Math.random() * arr.length)]
        const phone = `${Math.floor(100+Math.random()*800)}***${Math.floor(100+Math.random()*800)}`
        const modes = [
            `${rand(regions)}用户${phone}${rand(actions)}`,
            `${rand(regions)} · ${rand(topics)}`
        ]
        return rand(modes)
    }

    // 定时弹出胶囊：显示2.5s，每6s循环
    useEffect(() => {
        let showTimer: number | undefined
        const loop = () => {
            setPillText(makeRandomPillText())
            setPillVisible(true)
            showTimer = window.setTimeout(() => {
                setPillVisible(false)
            }, 2500)
        }
        // 先延迟一点点避免页面初载过于突兀
        const intervalId = window.setInterval(loop, 6000)
        // 首次延迟1s触发一次
        const first = window.setTimeout(loop, 1000)
        return () => {
            clearInterval(intervalId)
            clearTimeout(first)
            if (showTimer) clearTimeout(showTimer)
        }
    }, [])
    return (
        <div>
            <div className={styles.homebox}>
                <NavBar back={null} >春雨医生</NavBar>
                <div className={styles.seachbox}>
                    <div className={styles.customSearch}>
                        <span className={styles.searchIcon}>
                            <SearchOutline />
                        </span>
                        {searchValue === '' && (
                            <span className={styles.rollingPlaceholder} key={phIndex}>
                                {getRollingText()}
                            </span>
                        )}
                        <Input
                            placeholder=''
                            className={styles.searchInput}
                            value={searchValue}
                            onChange={handleSearchChange}
                            onEnterPress={handleSearchSubmit}
                        />
                        {searchValue && (
                            <span className={styles.clearIcon} onClick={clearSearchInput}>
                                <CloseOutline />
                            </span>
                        )}
                        <button className={styles.searchBtn} onClick={handleSearchSubmit}>搜索</button>
                    </div>
                    <div className={styles.imgbox}>
                        <img
                            className={styles.seaimg}
                            src={img}
                        />
                    </div>
                    {pillVisible && (
                        <div className={styles.pillToast}>
                            <span className={styles.pillText}>{pillText}</span>
                        </div>
                    )}
                </div>
            </div>
            <div className={styles.zibox}>
                <div className={styles.ziimg}>
                    <img src={dgimg} alt="" width={15} />{data?.believe_info.left_text}
                </div>
                <div>
                    <a href={data?.believe_info.url}>
                        <p>{data?.believe_info.right_text}</p>
                    </a>

                </div>
            </div>
            <div className={styles.textbox}>
                <div className={styles.textitemL} onClick={() => navigate('/consultation')}>
                    <img src={
                        data?.quick_ask_info.icon_url
                    } alt="" />

                </div>
                <div className={styles.textitemR}>
                    <div className={styles.textitemR1}>
                        <img src={
                            data?.find_doc_info.icon_url
                        } alt="" />

                    </div>
                    <div className={styles.textitemR2}>
                        <a href={data?.buy_drug_info.jump_url}>
                            <img src={
                                data?.buy_drug_info.icon_url
                            } alt="" />
                        </a>

                    </div>
                </div>
            </div>
            <div className={styles.swipbox}>
                <div className={styles.demoswiper}>
                    <ReactVantSwiper autoplay={3000}>
                        {
                            data?.banners && data.banners.length > 0 ? (
                                data.banners.map((item, ind) => (
                                    <ReactVantSwiper.Item key={ind}>
                                        <Image lazyload src={item.image_new} />
                                    </ReactVantSwiper.Item>
                                ))
                            ) : (
                                <ReactVantSwiper.Item>
                                    <div>
                                        加载中...
                                    </div>
                                </ReactVantSwiper.Item>
                            )
                        }
                    </ReactVantSwiper>
                </div>
            </div>
            <div>
                <div className={styles.scrollContainer}>
                    <div className={styles.scrollContent}>
                        <Grid className={styles.grid_menu} columns={7} gap={10}>
                            {
                                data?.important_position && data.important_position.length > 0 && data.important_position.map((img, ind) => (
                                    <div key={ind} className={styles.imageItem}>
                                        <dl>
                                            <dt>
                                                <a href={img.jump_url}>
                                                    <Image
                                                        src={img.icon}
                                                        className={styles.image}
                                                    />   
                                                </a>
                                            </dt>
                                            <dd>
                                                <p>{img.text}</p>
                                            </dd>
                                        </dl>
                                    </div>
                                ))
                            }
                        </Grid>
                    </div>
                </div>
            </div>
            <div>
                <Card title={data?.specialized_clinic.title} extra={data?.specialized_clinic.sub_title}>
                    <div className={styles.clinicbox}>
                        <div className={styles.clinicboxL}>
                            <a href={data?.specialized_clinic?.card_list?.[0].cy_redirect.target_scheme}>
                                {data?.specialized_clinic?.card_list?.[0]?.image && (
                                    <img
                                        src={data.specialized_clinic.card_list[0].image}
                                        alt={data.specialized_clinic.card_list[0].title}
                                    />
                                )}
                            </a>
                        </div>
                        <div className={styles.clinicboxR}>
                            <a href={data?.specialized_clinic?.card_list?.[1].cy_redirect.target_scheme}>
                                {data?.specialized_clinic?.card_list?.[1]?.image && (
                                    <img
                                        src={data.specialized_clinic.card_list[1].image}
                                        alt={data.specialized_clinic.card_list[1].title}
                                    />
                                )}
                            </a>
                        </div>
                    </div>
                </Card>
            </div>
            <div>
                <Doctor />
            </div>
            <div>
                <ServiceSection />
            </div>
            <div>
                <Tabs
                    activeKey={tabItems[activeIndex].key}
                    onChange={key => {
                        const index = tabItems.findIndex(item => item.key === key)
                        setActiveIndex(index)
                        swiperRef.current?.swipeTo(index)
                    }}
                    style={{
                        '--active-line-color': '#00CC66',
                        '--active-title-color': '#00CC66'
                    } as any}
                >
                    {tabItems.map(item => (
                        <Tabs.Tab title={item.title} key={item.key} />
                    ))}
                </Tabs>
                <Swiper
                    direction='horizontal'
                    loop
                    indicator={() => null}
                    ref={swiperRef}
                    defaultIndex={activeIndex}
                    onIndexChange={index => {
                        setActiveIndex(index)
                    }}
                >
                    <Swiper.Item>
                        <div className={styles.content}>
                            <ContentList 
                                contentType="healthNews" 
                                channelId="0" 
                                title="热点" 
                            />
                        </div>
                    </Swiper.Item>
                    <Swiper.Item>
                        <div className={styles.content_list}>
                            <ContentList 
                                contentType="topicCheck" 
                                channelId="0" 
                                title="专家科普"
                                showTabs={true}
                                tabs={[
                                    { key: 'all', label: '全部' },
                                    { key: 'audio', label: '语音',  },
                                    { key: 'qa', label: '简答',  },
                                    { key: 'article', label: '图文', },
                                    { key: 'video', label: '视频', }
                                ]}
                            />
                        </div>
                    </Swiper.Item>
                    <Swiper.Item>
                        <div className={styles.content}>
                            <ContentList 
                                contentType="healthNews" 
                                channelId="0" 
                                title="生活" 
                            />
                        </div>
                    </Swiper.Item>
                     <Swiper.Item>
                        <div className={styles.content}>
                            <ContentList 
                                contentType="healthNews" 
                                channelId="6" 
                                title="母婴" 
                            />
                        </div>
                    </Swiper.Item>
                     <Swiper.Item>
                        <div className={styles.content}>
                            <ContentList 
                                contentType="debunkNews" 
                                channelId="18" 
                                title="辟谣" 
                            />
                        </div>
                    </Swiper.Item>
                </Swiper>

            </div>
        </div>
    )
}

export default Index
